package regex.script.util;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

/**
 * User: regex | Kyle
 * Date: 25/07/11
 * Time: 10:19
 */
public abstract class IndexedMap<K, V> implements Map<K, V> {
    private int offset;
    private Entry[] entries;

    public IndexedMap() {
        this(10);
    }

    public IndexedMap(int cap) {
        offset = 0;
        entries = new Entry[cap];
    }

    @Override
    public int size() {
        return entries.length;
    }

    @Override
    public boolean isEmpty() {
        return entries.length < 0;
    }

    @Override
    public boolean containsKey(Object o) {
        for(Entry entry : entries) {
            if(entry.getKey().equals(o)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean containsValue(Object o) {
        for(Entry entry : entries) {
            if(entry.getVal().equals(o)) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public V get(Object o) {
        for(Entry entry : entries) {
            if(entry.getKey().equals(o)) {
                return (V) entry.getVal();
            }
        }
        return null;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public V put(K k, V v) {
        entries[offset++] = new Entry<K, V>(k, v, offset);
        return (V) entries[offset].getVal();
    }

    @SuppressWarnings({"unchecked", "UnusedAssignment"})
    @Override
    public V remove(Object o) {
        for(Entry entry : entries) {
            if(entry.getKey().equals(o)) {
                return (V) (entry = null);
            }
        }
        return null;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        for(K key : map.keySet()) {
            for(V val : map.values()) {
                put(key, val);
            }
        }
    }

    @Override
    public void clear() {
        for(int i = 0; i < entries.length; i++) {
            entries[i] = null;
        }
    }

    private class Entry<K, V> {
        private K key;
        private V val;
        private int index;

        public Entry(K key, V val, int index) {
            this.key = key;
            this.val = val;
            this.index = index;
        }

        public K getKey() {
            return key;
        }

        public V getVal() {
            return val;
        }

        public int getIndex() {
            return index;
        }
    }
}
